<template>
  <div class="miniprogram-upload">
    <el-dialog
      v-model="dialogVisible"
      title="上传到微信小程序平台"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="uploadForm" label-width="120px">
        <el-alert
          title="开发小程序上传"
          type="success"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <p><strong>开发小程序 APPID:</strong> wxbfce7651b040d62a</p>
          <p><strong>平台 APPID:</strong> wx0813f5516086ef98</p>
          <p style="margin-top: 8px; color: #67C23A;">✓ 已配置私钥认证，可直接上传</p>
        </el-alert>

        <el-form-item label="授权小程序" required>
          <el-input
            v-model="uploadForm.authAppid"
            placeholder="wxbfce7651b040d62a"
            disabled
            readonly
          >
            <template #prepend>AppID</template>
          </el-input>
          <div class="form-tip" style="color: #67C23A;">
            ✓ 已自动填入开发小程序 APPID
          </div>
        </el-form-item>

        <el-form-item label="版本号">
          <el-input
            v-model="uploadForm.version"
            placeholder="自动生成时间戳版本"
            clearable
          >
            <template #append>
              <el-button @click="generateVersion" :loading="generatingVersion">
                生成
              </el-button>
            </template>
          </el-input>
          <div class="form-tip">格式: YYYY.MMDD.HHMM 或 x.y.z</div>
        </el-form-item>

        <el-form-item label="版本描述">
          <div style="display: flex; gap: 10px; align-items: flex-start;">
            <el-input
              v-model="uploadForm.desc"
              type="textarea"
              :rows="3"
              placeholder="点击生成按钮自动填充"
              style="flex: 1;"
            />
            <el-button @click="generateDesc" :loading="generatingDesc" style="height: 32px;">
              生成
            </el-button>
          </div>
          <div class="form-tip">自动生成：构建域名 + config版本号 + 构建时间</div>
        </el-form-item>

        <el-form-item label="机器人编号">
          <el-input-number
            v-model="uploadForm.robot"
            :min="1"
            :max="30"
            controls-position="right"
          />
          <div class="form-tip">范围: 1-30</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" :disabled="uploading">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="handleUpload"
            :loading="uploading"
            :disabled="!canUpload"
          >
            {{ uploading ? "上传中..." : "开始上传" }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传进度对话框 -->
    <el-dialog
      v-model="progressVisible"
      title="上传进度"
      width="500px"
      :close-on-click-modal="false"
      :show-close="!uploading"
    >
      <div class="upload-progress">
        <el-progress
          :percentage="uploadProgress"
          :status="uploadStatus"
          :stroke-width="20"
        />
        <p class="progress-text">{{ uploadMessage }}</p>

        <div v-if="uploadResult" class="upload-result">
          <el-result
            :icon="uploadResult.success ? 'success' : 'error'"
            :title="uploadResult.success ? '上传成功' : '上传失败'"
          >
            <template #sub-title>
              <div v-if="uploadResult.success">
                <p>版本: {{ uploadResult.data?.version }}</p>
                <p>{{ uploadResult.data?.desc }}</p>
                <p style="margin-top: 10px; color: #409EFF;">
                  请登录<a href="https://mp.weixin.qq.com" target="_blank" style="color: #409EFF;">微信公众平台</a>查看上传结果
                </p>
              </div>
              <div v-else>
                <p>{{ uploadResult.message }}</p>
              </div>
            </template>
          </el-result>
        </div>
      </div>

      <template #footer v-if="!uploading">
        <el-button type="primary" @click="closeProgressDialog">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from "vue";
import axios from "axios";
import { WECHAT_CONFIG } from "../utils/constants.js";

export default {
  name: "MiniprogramUpload",
  props: {
    projectId: {
      type: String,
      required: true,
    },
    platform: {
      type: String,
      default: "mp-weixin",
    },
  },
  setup(props, { emit }) {
    const dialogVisible = ref(false);
    const progressVisible = ref(false);
    const uploading = ref(false);
    const uploadProgress = ref(0);
    const uploadStatus = ref("");
    const uploadMessage = ref("");
    const uploadResult = ref(null);
    const generatingVersion = ref(false);
    const generatingDesc = ref(false);

    const uploadForm = ref({
      authAppid: WECHAT_CONFIG.DEV_MINIPROGRAM_APPID, // 默认使用开发小程序APPID
      version: "",
      desc: "",
      robot: 1,
    });

    // 单个上传时，APPID已经默认填充，始终可以上传
    const canUpload = computed(() => true);

    const open = () => {
      dialogVisible.value = true;
      resetForm();
    };

    const resetForm = () => {
      uploadForm.value = {
        authAppid: WECHAT_CONFIG.DEV_MINIPROGRAM_APPID, // 重置时也使用开发小程序APPID
        version: "",
        desc: "",
        robot: 1,
      };
      uploadResult.value = null;
    };

    const generateVersion = async () => {
      generatingVersion.value = true;
      try {
        const response = await axios.get("/api/miniprogram/generate-version");
        if (response.data.success) {
          uploadForm.value.version = response.data.version;
        }
      } catch (error) {
        console.error("生成版本号失败:", error);
      } finally {
        generatingVersion.value = false;
      }
    };

    const generateDesc = async () => {
      generatingDesc.value = true;
      try {
        // 自动从构建配置读取域名
        const response = await axios.get(`/api/miniprogram/generate-desc/${props.projectId}`);
        if (response.data.success) {
          uploadForm.value.desc = response.data.desc;
        }
      } catch (error) {
        console.error("生成版本描述失败:", error);
        // 如果失败（比如从历史记录上传，项目目录已被清理），使用默认描述
        const now = new Date();
        const timestamp = now.toLocaleString("zh-CN");
        uploadForm.value.desc = `历史构建上传\n上传时间: ${timestamp}`;
      } finally {
        generatingDesc.value = false;
      }
    };

    const handleUpload = async () => {
      await singleUpload();
    };

    const singleUpload = async () => {
      uploading.value = true;
      uploadProgress.value = 0;
      uploadMessage.value = "准备上传...";
      progressVisible.value = true;
      dialogVisible.value = false;

      try {
        uploadProgress.value = 30;
        uploadMessage.value = "正在上传小程序代码...";

        const response = await axios.post("/api/miniprogram/upload", {
          projectId: props.projectId,
          authAppid: uploadForm.value.authAppid,
          version: uploadForm.value.version || undefined,
          desc: uploadForm.value.desc || undefined,
          robot: uploadForm.value.robot,
        });

        uploadProgress.value = 100;
        uploadStatus.value = "success";
        uploadMessage.value = "上传完成!";
        uploadResult.value = response.data;

        emit("upload-success", response.data);
      } catch (error) {
        console.error("上传失败:", error);
        uploadProgress.value = 100;
        uploadStatus.value = "exception";
        uploadMessage.value = "上传失败!";
        uploadResult.value = {
          success: false,
          message: error.response?.data?.message || error.message,
        };

        emit("upload-error", error);
      } finally {
        uploading.value = false;
      }
    };

    const closeProgressDialog = () => {
      progressVisible.value = false;
      resetForm();
    };

    return {
      dialogVisible,
      progressVisible,
      uploading,
      uploadProgress,
      uploadStatus,
      uploadMessage,
      uploadResult,
      generatingVersion,
      generatingDesc,
      uploadForm,
      canUpload,
      open,
      generateVersion,
      generateDesc,
      handleUpload,
      closeProgressDialog,
    };
  },
};
</script>

<style scoped>
.miniprogram-upload {
  display: inline-block;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.upload-progress {
  padding: 20px 0;
}

.progress-text {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

.upload-result {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
